package com.qhit.jdbc;


import com.qhit.jdbc.bean.Student;
import com.qhit.jdbc.bean.User;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class JDBCUserTest {
//  （1）通过3种方式获得User类对应的反射对象
    @Test
    public void getUser() throws ClassNotFoundException {
        //方式一 通过类全名
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //方式二 通过类类型
        Class<User> userClass1 = User.class;
        //方式三 通过用户对象调用getClass方法获得
        Class<? extends User> userClass2 = new User().getClass();
    }
//	（2）通过2种方式获得User类的构造方法对应的反射对象Constructor
    @Test
    public void getConstructor() throws ClassNotFoundException, NoSuchMethodException {
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //方式一
        Constructor<?> constructor = userClass.getConstructor();
        //方式二
        Constructor<?> declaredConstructor = userClass.getDeclaredConstructor(Integer.class, String.class, Integer.class);
    }
//	（3）通过2种方式通过反射的方式获得User类的实例对象。
    @Test
    public void getUserObject() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class<Student> userClass = (Class<Student>) Class.forName("com.qhit.jdbc.bean.User");
        //方式一 User类类型对象创建
        Student student = userClass.newInstance();
        //方式二 构造方法对象创建
        Student student1 = userClass.getConstructor().newInstance();
    }
//	（4）通过Field对真实对象的属性进行读写操作
    @Test
    public void getField() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        User user = new User(1,"张三",14);
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //得到属性对象 username
        Field usernameField = userClass.getDeclaredField("username");
        //设置属性访问权限  允许访问
        usernameField.setAccessible(true);
        //设置user对象中的username属性值为：李四
        usernameField.set(user,"李四");
        //获取user对象的username属性值
        System.out.println(usernameField.get(user));
    }
//	（5）通过Method对象，操作真实对象的show()方法
    @Test
    public void getMethod() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User(1,"张三",14);
        Class<?> userClass = Class.forName("com.qhit.jdbc.bean.User");
        //show方法的对象
        Method showMethod = userClass.getMethod("show");
        //调用user对象的show方法
        showMethod.invoke(user);
    }
}